<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Cahced entity factory
 * 
 * Entity factory, responsible for creating entities from RDF data, used by a data source. Caches created entities by subject URI.
 */
class entityresolution_entityfactory_Cached implements entityresolution_EntityFactory
{
	/**
	 * Entities by subject URI.
	 * @var array[string]entityresolution_Entity
	 */
	protected $entities = array();
	
	/**
	 * Data filter chain.
	 * @var entityresolution_DataFilterChain
	 */
	protected $dataFilterChain;
	
	/**
	 * Create a new cached entity factory instance.
	 * @param entityresolution_DataFilterChain $dataFilterChain data filter chain
	 */
	public function __construct($dataFilterChain)
	{
		$this->dataFilterChain = $dataFilterChain;
	}

	/**
	 * Create an entity using the RDF data specified, or return a cached instance.
	 * @param simplerdf_RdfDocument $rdfDocument RDF data
	 * @return entityresolution_Entity entity
	 */
	public function createEntity($rdfDocument, $subjectUri)
	{
		$entity = $this->entities[$subjectUri];
		
		if($entity === null)
		{
			// entity does not exist in the cache, create an entity
			$entity = new entityresolution_Entity($rdfDocument, $subjectUri);
			
			// call the data filter chain
			$this->dataFilterChain->filterSourceData($entity);
			
			// cache the entity
			$this->entities[$subjectUri] = $entity;
		}
		
		return $entity;
	}
}